package org.freemarker.core.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.freemarker.core.dao.ContactDao;
import org.freemarker.core.model.Contact;
import org.freemarker.core.model.Gender;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class ContactDaoImpl extends EntityJpaDaoImpl<Contact> implements
		ContactDao {

	public ContactDaoImpl() {
		setClazz(Contact.class);
	}

	@Override
	public long getDaoContactCountOnGender(Gender g) {
		Query q = entityManager
				.createQuery("SELECT count(*) FROM " + clazz.getName()
						+ " c WHERE c.gender=" + "'" + g.name() + "'");
		List<?> resultList = q.getResultList();

		return (Long) resultList.get(0);
	}
	@Override
	public Contact getContactBySecurityNumber(String securityNumber) {
		

		Query q = super.entityManager.createQuery("FROM "
				+ clazz.getName() + " WHERE security_number = '" + securityNumber +"'");
		Contact result = (Contact) q.getSingleResult();
		

		return result;
	}
	
	
	public void updateBySecurityNumber(Contact c){
		Query q = super.entityManager.createQuery("UPDATE "
				+ clazz.getName() + " SET birthdate = '" + c.getBirthdate() 
				+ "', first_name = '" + c.getFirstname() +"', last_name = '" 
				+ c.getLastname() + "', email = '" + c.getEmail() 
				+ "', gender = '" + c.getGender() + "', telephone = '" 
				+ c.getTelephone() +"' WHERE security_number = '"
				+ c.getSecurityNumber() + "'" );
		
		q.executeUpdate();
		entityManager.flush();
	}
	
}
